import store from '../store/index.js';
import {
	getUserInfo
} from '../network/me.js'
import {
	getGroupList
} from '../network/chat.js'
import {WS} from '../network/requestUrl.js'

let ws = null

export async function setGather() {
	const result = await getGroupList()
	// console.log(result)
	if (!result.flag) return;
	let list = result.data.map(item => {
		item.number = 0
		return item
	})
	let obj = {}
	list.forEach(item => obj[item.id] = item)
	store.commit('setGather', obj)
}


export function setLoginStatus(isLogin) {
	uni.setStorageSync('isLogin', isLogin)
}

// 网络请求
export function request(ars) {
	return new Promise((resolve, reject) => {
		$uni.request({
			...ars,
			success: resolve,
			fail: reject
		})
	})
}

// 建立连接
export function connect() {
	// ws = = uni.connectSocket({
	//    url: 'wss://www.example.com/socket', //仅为示例，并非真实接口地址。
	//    complete: ()=> {}
	// });
	console.log('开始连接')
	ws = uni.connectSocket({
		url: WS,
		fail: () => {
			uni.showToast({
				title: '连接失败',
				icon: 'none'
			})
		}
	})

	uni.onSocketOpen(function(res) {
		console.log('WebSocket连接已打开！');
		uni.sendSocketMessage({
			data: JSON.stringify({
				type: '0',
				data: {
					userId: store.state.userInfo.user_id
				}
			})
		});

		message()
	});
}

// 接收信息
export function message() {
	uni.onSocketMessage(async function(res) {
		console.log('接收信息')
		let info = JSON.parse(res.data)
		
		// 接收地图消息
		if (info.type == "2") {
			console.log(info.data)
			return void storagePosition(info.data)
		}
		
		// 聊天信息
		const result = await getUserInfo(info.clientId, false)
		// console.log(result.data)
		// 设置聊天记录
		const lost_id = store.state.userInfo.role == '家属' ? info.clientId : info.lost_id;
		console.log(lost_id)
		store.commit('setChat', {
			lost_id,
			chat: {
				userId: info.clientId,
				nickName: result.data[0].name,
				message: info.msg,
				icon: result.data[0].url
			}
		})

		//判断当前页面栈是否处于聊天页面中

		// 设置群聊列表
		let page = getCurrentPages()
		if (page[page.length - 1].route != "pages/chatList/chatDetail/chatDetail") {
			store.commit('setGatherNumber', {
				lost_id,
				number: store.state.gather[lost_id].number + 1
			})
			console.log(store.state.gather)
			uni.showToast({
				title: '你有信息',
				duration: 500,
				icon: 'none'
			})
		}
	})
}

// 发送消息
export function sendMsg(data, type="1") {
	console.log(type, data)
	uni.sendSocketMessage({
		data: JSON.stringify({
			type,
			data
		})
	});
}

export function storagePosition(data) {
	uni.setStorageSync('position', JSON.stringify(data))
}

export function dateDiffer(a, b) {
	return (new Date(a)).getDate() - (new Date(b)).getDate()
}
